package com.yzh.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/model")
public class ModelTest {
    /**
     * 流程模型定义
     * @param request
     * @param response
     */
    @RequestMapping("/create")
    public void createModel(HttpServletRequest request, HttpServletResponse response){
        try{
            String modelName = "请假流程";
            String modelKey = "modelKey";
            String description = "description";
            //初始化模型 开始
            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            RepositoryService repositoryService = processEngine.getRepositoryService();
            //封装模型对象基础参数json字符串固定格式
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.replace("stencilset", stencilSetNode);
            //标识key
            ObjectNode propertiesNode = objectMapper.createObjectNode();
            propertiesNode.put("process_id", modelKey);
            editorNode.replace("properties", propertiesNode);

            Model modelData = repositoryService.newModel();
            //封装模型josn
            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            //名称
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, modelName);
            //版本
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            //描述
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            //元数据 json格式
            modelData.setMetaInfo(modelObjectNode.toString());
            //模型名称
            modelData.setName(modelName);
            //模型key
            modelData.setKey(modelKey);
            //保存模型
            repositoryService.saveModel(modelData);
            //存储模型对象基础数据 act_ge_bytearray
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
            response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
        }catch (Exception e){
        }
    }

}
